<template>
  <div>
    <FormPanel ref="topFilterFormPanel" :list="topFilterList" :cols="4" :labelWidth="90" :isSubmitBtn="false" @formChange="changeHandle"></FormPanel>
    <FilterTable
      ref="innerTable"
      columnsRef="partPartOutboundInternalReceiveIndex"
      :columns="columns"
      :dataSource="tableData"
      :datakey="'rows'"
      :onSyncTableData="handlData"
      :onRowSelectChange="changeSelectRows"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <!--:auth-list="auths" auth-mark="/part/out/inner/audit"
    :auth-list="auths" auth-mark="/part/out/inner/save"
    :auth-list="auths" auth-mark="/part/out/inner/outBound"
    -->
      <template slot="moreActions">
        <!-- <el-button :disabled="this.isFinished" @click="deleteHandle()">删 除</el-button> -->
      </template>
      <template slot="controls">
        <el-button size="small" type="primary" @click="() => deleteRow()">删除选中数据</el-button>
        <el-button size="small" type="primary" :disabled="createFlag" @click="createFun">新建</el-button>
        <el-button size="small" type="primary" :disabled="addFlag" @click="addNewPartFun">新增</el-button>
        <!-- <el-button size="small" type="primary" :disabled="returnFlag" @click="returnPartFun">退料</el-button> -->
        <!-- <AjaxButton size="small" type="primary" :disabled="saveFlag" :click="save">保存</AjaxButton> -->
        <AjaxButton size="small" type="primary" :disabled="saveFlag" :click="save">保存</AjaxButton>
        <!-- <AjaxButton size="small" type="primary" :disabled="auditFlag" :click="audit">审核</AjaxButton> -->
        <!-- <AjaxButton size="small" type="primary" :disabled="auditFlag" :click="audit">审核</AjaxButton> -->
        <AjaxButton size="small" type="primary" :disabled="inFlag" :click="inStock">出库</AjaxButton>
        <!-- <AjaxButton size="small" type="primary" :disabled="inFlag" :click="inStock">出库</AjaxButton> -->
        <AjaxButton size="small" type="primary" :disabled="cancelFlag" :click="cancel">取消</AjaxButton>
        <AjaxButton size="small" type="primary" :disabled="quitFlag" :click="quit">作废</AjaxButton>
        <AjaxButton size="small" type="primary" :disabled="printFlag" icon="el-icon-printer" :click="print">打印</AjaxButton>
      </template>
    </FilterTable>
    <Drawer :visible.sync="showAddNewPart" title="内部领用新增" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addNewPart :forReturn="isReturn" :ptype="this.ptype" @close="closeHandler" @addNewPart="setNewPartData" />
    </Drawer>
    <BaseDialog :visible.sync="showEditPart" title="内部领用编辑" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editPartPage :editRowData="editRow" :forReturn="isReturn" @close="closeHandler" @editPart="editPartData" />
    </BaseDialog>
    <BaseDialog :visible.sync="showReturn" title="内部领用退料" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <BackPart :partInfo="partInfo" :parnArr="tableData" @confirm="confirmTl" @cancel="showReturn = false" />
    </BaseDialog>
    <BaseDialog :visible.sync="showSearchReceiptor" title="领用人选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchReceiptor :pickerId="this.topFilterList[1].initialValue" @close="closeHandler" @addReceiptor="setReceiptor" />
    </BaseDialog>
    <BaseDialog :visible.sync="showSearchInternalReceive" title="领用单" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchInternalReceive :orderNo="this.topFilterList[0].initialValue" :ptype="this.ptype" :salerList="salerList" @close="closeHandler" @showOrder="showOrderDetail" />
    </BaseDialog>
    <!-- 打印 -->
    <div v-if="dy">
      <BasePrint ref="print" :data="SalesprintList" template="templateInternalReceive" />
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import _ from 'lodash';
import searchReceiptor from './searchReceiptorPage';
import addNewPart from './addNewPartPage';
import searchInternalReceive from './searchInternalReceivePage';
import editPartPage from './editPartPage';
import BackPart from './BackPart';
import { exportExcelFile, arrayObjDeWeight } from '@/utils/index';
import { queryUnitCode } from '@/api/repair/batchEventManagement/activityDistribution';
import {
  saveOrder,
  showDetailRequest,
  showDetailRequestByType,
  deleteOrder,
  queryPartIfBelowZero,
  stockIn,
  auditOrder,
  printData,
  getOrgByOrgType,
  getUserByOrgId
} from '@/api/part/partOutbound/internalReceive/index';

// 查询与员工用户有关的信息
import { searchRoleByCode } from '@/api/common/empSelect/index';
// 获取员工
import { searchDealerOrg, getDealerUser } from '@/api/customerRepair/customerComplaint/customerComplaintReception';
// 获取部门树
import { getOrgsTree } from '@/api/common/org/companyOrgManage/index';

import dictCode from '@/utils/dictCode';
import { authority } from '@/utils/authMixin';
import { getStorageList } from '@/api/part/partInventory/adjustInventory/index';
import { getOrgType, getDealerArea } from '@/api/potenCus/customer/potenCusManage';
import { getWorkerGroups, getOrgList } from '@/api/repair/repairBusiness/instituteDefined';
import { dealerPrintApi } from '@/api/repair/index.js';

export default {
  name: 'inernalReceive',
  components: {
    searchInternalReceive,
    searchReceiptor,
    addNewPart,
    editPartPage,
    BackPart
  },
  mixins: [dictionary, authority],
  data() {
    this.conf = { add: '新增', edit: '编辑', show: '显示' };
    this.innerTableData = null;
    this.saveData = null;
    return {
      cunBm: [], // 存部门下拉框数据
      cunUserList: [], // 存所有人的数组
      receiptorList: [],
      selectRows: [], // 选中行数据
      cunId: '', // 存打印id
      SalesprintList: {},
      dy: false,
      createFlag: false,
      addFlag: true,
      returnFlag: true,
      saveFlag: true,
      auditFlag: true,
      inFlag: true,
      cancelFlag: true,
      quitFlag: true,
      printFlag: true, // 原 true
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchParams: {},
      innerID: '',
      isReturn: false, // 用于判断是新增还是退料
      showSearchReceiptor: false,
      showSearchInternalReceive: false,
      showEditPart: false,
      showAddNewPart: false,
      showReturn: false,
      isFinished: false,
      editRow: {}, // 保存修改行数据
      inTableListData: [],
      tableData: [],
      deleteRows: '', // 删除行ITEM_ID,
      salerList: {}, // 员工对象
      partInfo: {},
      department: [], // 部门字典
      postSalesUser: [], //售后人员信息
      postSalesUserList: [],
      autoPrint: 'false', // 自动打印
      printParams: {} // 打印参数
    };
  },
  watch: {
    receiptNo(nVal, oVal) {
      console.log(nVal, 'nVal');
      if (!_.isNil(nVal)) {
        // this.topFilterList.find(x => x.fieldName == 'receiptor').disabled = true;
        console.log('disabled=true');
      }
    }
  },
  computed: {
    ptype() {
      return this.$route.meta.ptype;
    },
    receiptNo() {
      return this.topFilterList.find(x => x.fieldName == 'receiptNo').initialValue;
    }
  },
  created() {
    this.getDealerUser();
    this.getOrgByOrgType();
    this.getPostSalesUser();
    this.getStorageList();
    this.$nextTick(() => {
      this.getSalerList();
    });
  },
  mounted() {
    this.innerTableData = this.$refs.innerTable.$refs.pageTable;
    this.getUnit();
    // this.queryPrintParams(); // 查询打印参数
  },
  methods: {
    handlData(val) {
      this.inTableListData = val;
    },
    async getSalerList() {
      let emps = await getDealerUser();
      let obj = {};
      let data = arrayObjDeWeight(emps.data, 'userId');
      data.map(item => {
        obj[item.userId] = item.employeeName;
      });
      this.salerList = obj;
      this.topFilterList.find(x => x.fieldName === 'orgCode').itemList = this.department;
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '领用单号',
          fieldName: 'receiptNo',
          placeholder: '请输入...',
          disabled: false,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.searchInternalReceiveFun()}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '部门',
          fieldName: 'orgCode',
          itemList: [],
          placeholder: '请选择...',
          disabled: true
          // unitRender: props => {
          //   return <el-button icon="el-icon-search" onClick={() => this.searchReceiptorFun()}></el-button>;
          // }
        },
        {
          type: 'SELECT',
          label: '申请人',
          fieldName: 'receiptor',
          placeholder: '请选择...',
          itemList: [],
          rules: [{ required: true, message: '请选择申请人', trigger: 'change' }],
          disabled: true,
          change: val => this.openSearch(val),
          filterable: true
        },
        { type: 'DATE', label: '申请日期', fieldName: 'receiptDate', placeholder: '请输入...', valueFormat: 'yyyy-MM-dd', disabled: true },
        { type: 'INPUT', label: '备注', fieldName: 'remark', placeholder: '请输入...', disabled: true }
        // {
        //   type: 'CHECKBOX',
        //   label: '打印单据',
        //   fieldName: 'needPrint',
        //   noResetable: true,
        //   initialValue: 'true',
        //   options: {
        //     trueValue: 'true',
        //     falseValue: 'false'
        //   }
        // change: val => (this.autoPrint = val)
        // }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 90,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button disabled={props.row.IS_FINISHED == 10041001 || props.row.OUT_QUANTITY < 0} size="mini" type="text" onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
                <el-button disabled={props.row.OUT_QUANTITY < 0 || props.row.IS_FINISHED != 10041001} size="mini" type="text" onClick={() => this.returnPartFun(props.row)}>
                  退料
                </el-button>
              </div>
            );
          }
        },
        { title: '仓库', dataIndex: 'STORAGE_CODE', sorter: true, editable: true, editType: 'select', editItems: [], editRequired: 'false', disabled: true },
        { title: '库位', dataIndex: 'STORAGE_POSITION_CODE', sorter: true, filter: true, filterType: 'input' },
        { title: '配件代码', dataIndex: 'PART_NO', sorter: true, filter: true, filterType: 'input' },
        { title: '配件名称', dataIndex: 'PART_NAME', showOverflowTooltip: true, sorter: true, filter: true, filterType: 'input' },
        // {
        //   title: '是否审核',
        //   dataIndex: 'IS_AUDIT',
        //   sorter: true,
        //   editable: false,
        //   editType: 'select',
        //   editItems: this.createDictList('1004'),
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1004')
        // },
        {
          title: '是否出库',
          dataIndex: 'IS_FINISHED',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: this.createDictList(1004),
          filter: true,
          filterItems: this.createDictList('1004'),
          filterType: 'checkbox'
        },
        { title: '出库数量', dataIndex: 'OUT_QUANTITY', sorter: true, filter: true, precision: 2, filterType: 'number' },
        { title: '含税成本单价', dataIndex: 'COST_PRICE', sorter: true, filter: true, precision: 2, filterType: 'number' },
        { title: '含税成本金额', dataIndex: 'COST_AMOUNT', sorter: true, filter: true, precision: 2, filterType: 'number' },
        // { title: '出库单价', dataIndex: 'OUT_PRICE', sorter: true, filter: true, precision: 2, filterType: 'number' },
        // { title: '出库金额', dataIndex: 'OUT_AMOUNT', sorter: true, filter: true, precision: 2, filterType: 'number' },
        // {title: '价格系数',  dataIndex: 'PRICE_RATE',  sorter: true,  filter: true, filterType: 'input'},
        // {title: '借进数量',  dataIndex: 'BORROW_QUANTITY',  sorter: true,  filter: true, filterType: 'input'},
        // {title: '借出数量',  dataIndex: 'LEND_QUANTITY',  sorter: true,  filter: true, filterType: 'input'},
        // { title: 'ITEM_ID', dataIndex: 'ITEM_ID', sorter: true, filter: true, hidden: true, filterType: 'input' },
        // { title: 'FLAG', dataIndex: 'FLAG', sorter: true, filter: true, hidden: true, filterType: 'input' },
        { title: '计量单位', dataIndex: 'UNIT_CODE', sorter: true, dictItems: [], filter: true, filterType: 'checkbox' }
      ];
    },
    // 是否审核
    createAuditText(val) {
      if (val == '10041001') {
        return '审核通过';
      } else {
        return '待审核';
      }
    },
    // 获取售后人员信息
    async getPostSalesUser() {
      const res = await searchRoleByCode({ role: 10061011 });
      console.log('res.data:', res.data);
      this.postSalesUser = res.data;
      let data = arrayObjDeWeight(res.data, 'userId');
      this.postSalesUserList = this.topFilterList.find(item => item.fieldName === 'receiptor').itemList = data.map(x => ({ text: x.employeeName, value: x.userId }));
    },
    // 获取部门字典
    async getOrgByOrgType() {
      const res = await getOrgByOrgType({ orgType: '15061001,15061002,15061003,15061004,15061005,15061006,15061007,15061008,15061009,15061010,15061011,15061012,15061013,15061014,15061015' });
      console.log(res, 'ressss');
      let data = arrayObjDeWeight(res.data, 'orgId');
      // this.receiptorList = res.data;
      this.department = this.topFilterList.find(item => item.fieldName === 'orgCode').itemList = data.map(x => ({ text: x.orgName, value: x.orgId + '' }));
    },
    // 获取仓库
    async getStorageList() {
      const storageData = (await getStorageList({})).data;
      // console.log(storageData, 'storageData');
      this.columns.find(x => x.dataIndex === 'STORAGE_CODE').editItems = storageData.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    },
    openSearch(val) {
      if (val) {
        // console.log('val::', val);
        // console.log('postSalesUser::', this.postSalesUser);
        // console.log('ssss::', this.postSalesUser.find(x => x.userId == val).orgId);
        console.log(
          'itemList::',
          this.topFilterList.find(item => item.fieldName === 'orgCode')
        );
        this.topFilterList.find(item => item.fieldName === 'orgCode').initialValue = this.postSalesUser.find(x => x.userId == val).orgId + '';
      } else {
        this.topFilterList.find(item => item.fieldName === 'orgCode').initialValue = '';
      }

      // this.topFilterList.find(item => item.fieldName === 'orgCode').initialValue = orgId ? orgId + '' : null;
    },

    createFun() {
      this.createFlag = true;
      this.saveFlag = false;
      this.returnFlag = true;
      this.cancelFlag = false;
      this.addFlag = false;
      this.printFlag = true;
      this.topFilterList[0].disabled = true;
      this.topFilterList[1].disabled = true;
      this.topFilterList[2].disabled = false;
      this.topFilterList[0].initialValue = '';
      this.topFilterList[1].initialValue = undefined;
      this.topFilterList[3].initialValue = moment().format('YYYY-MM-DD');
      console.log('time::', moment().format('YYYY-MM-DD'));
      this.topFilterList[4].disabled = false;
      this.topFilterList[4].initialValue = '';
      this.tableData = [];
      this.deleteRows = '';
      this.isFinished = false;
      this.editRow = {};
      // this.topFilterList = [...this.topFilterList];
    },
    changeSelectRows(val) {
      this.selectRows = val;
    },
    async getUnit() {
      const res = await queryUnitCode();
      console.log('getUnit res::', res);
      let data = arrayObjDeWeight(res.data, 'UNIT_CODE');
      this.columns.find(x => x.dataIndex == 'UNIT_CODE').dictItems = data.map(x => ({ value: x.UNIT_CODE + '', text: x.UNIT_NAME }));
    },
    deleteRow() {
      if (this.selectRows.length == 0) {
        this.$notify.error({ title: '提示信息', message: '请选中数据' });
        return;
      }
      let out = this.selectRows.find(x => x.IS_FINISHED == '10041001');
      if (!out) {
        for (const item of this.selectRows) {
          if (item.ITEM_ID) {
            console.log(item, 'item.ITEM_ID');
            this.deleteRows = item.ITEM_ID + ',' + this.deleteRows;
          }
        }
        this.innerTableData.EXECUTE_DELETE(this.selectRows);
        this.saveFlag = false;
        this.inFlag = true;
        this.quitFlag = true;
      } else {
        this.$notify.error({ title: '提示信息', message: '选中配件中存在已出库，无法删除配件!' });
      }
    },
    async save() {
      try {
        this.saveData = null;
        this.$refs.topFilterFormPanel.SUBMIT_FORM();
        if (this.saveData != null) {
          // this.jsonToHump(this.inTableListData);
          let tableList = this.inTableListData;
          if (tableList.length == 0) {
            return this.$notify.error({ title: '提示信息', message: '请添加配件!' });
          }
          console.log(tableList);
          tableList.forEach(x => {
            if (x.UNIT_CODE != null && x.UNIT_CODE != undefined && x.UNIT_CODE != '') {
              x.UNIT = x.UNIT_CODE;
            }
          });
          // this.addFlag = false;
          // this.returnFlag = false;
          // this.inFlag = false;
          // this.cancelFlag = false;
          // this.saveFlag = true;
          let data = {
            ...this.fetchParams,
            items: this.deleteRows,
            dms_table: tableList
          };
          data.orgName = this.department.find(x => x.value == data.orgCode).text;
          // 数据分离->保存
          if (this.ptype) {
            data.ptype = this.ptype;
          }
          let res = await saveOrder(data);
          if (res.resultCode === 200) {
            this.$notify.success({ title: '提示信息', message: '保存成功!' });
            var dataInfo = res.data.split(';');
            this.topFilterList[0].disabled = true;
            this.topFilterList[2].disabled = true;
            this.topFilterList[0].initialValue = dataInfo[0];
            this.deleteRows = '';
            // 审核按钮解禁
            this.quitFlag = false;
            this.auditFlag = false;
            this.isFinished = true;
            this.returnFlag = true;
            this.inFlag = false;
            this.auditFlag = true;
            this.addFlag = false;
            this.saveFlag = true;
            this.tableData = [];
            this.showOrderItemDetail(dataInfo[1]);
            this.cunId = dataInfo[1];
          }
        }
      } catch (e) {
        console.log('e::::', e);
      }
    },
    async audit() {
      // 审核通过后，删除、编辑和退料按钮应置灰
      console.log(11111, this.inTableListData);

      let res = await auditOrder(this.inTableListData[0].PART_INNER_ID);
      if (res.resultCode == 200) {
        this.isFinished = true;
        this.returnFlag = true;
        this.inFlag = false;
        this.auditFlag = true;
        this.addFlag = false;
        this.saveFlag = true;
        this.quitFlag = true;
        console.log(this.saveFlag, '保存');
        console.log(this.inFlag, '出库');
        console.log(this.auditFlag, '审核');
        this.$notify.success({ title: '提示信息', message: '单据审核成功!' });
        let id = res.data.id;
        this.tableData = [];
        this.columns = [...this.columns];
        this.showOrderItemDetail(id);
      } else {
        return this.$notify.error({ title: '提示信息', message: res.data.errMsg || '单据审核失败!' });
      }
      console.log('审核');
    },
    showOrderDetail(val) {
      this.createFlag = true;
      this.saveFlag = false;
      this.cancelFlag = false;
      this.addFlag = false;
      this.auditFlag = false;
      this.printFlag = false;
      this.quitFlag = val[0].STATUS == 0 ? false : true;
      this.topFilterList[0].disabled = true;
      this.topFilterList[1].disabled = true;
      this.topFilterList[2].disabled = true;
      this.topFilterList[3].disabled = true;
      this.topFilterList[4].disabled = val[0].STATUS == 0 ? false : true;
      this.topFilterList[0].initialValue = val[0].RECEIPT_NO;
      this.topFilterList[1].initialValue = val[0].DEPT_CODE;
      this.topFilterList[2].initialValue = val[0].EMPLOYEE_NO;
      this.topFilterList[3].initialValue = val[0].RECEIPT_DATE;
      this.topFilterList[4].initialValue = val[0].REMARK;
      this.cunId = val[0].PART_INNER_ID;
      this.tableData = [];
      this.columns = [...this.columns];
      this.showOrderItemDetail(val[0].PART_INNER_ID);
      this.showSearchInternalReceive = false;
    },
    async showOrderItemDetail(inId) {
      this.innerID = inId;
      let infodata = await showDetailRequest(inId);
      // 查询条件增加
      // let queryParams = { id: inId };
      // if (this.ptype) {
      //   queryParams.ptype = this.ptype;
      // }
      // let infodata = await showDetailRequestByType(queryParams);
      if (infodata.resultCode === 200) {
        this.innerTableData.EXECUTE_INSERT(infodata.data);
        this.innerTableData.EXECUTE_RESET_HEIGHT();
        // this.quitFlag = true;
        // 是否审核，判断是否解禁
        if (infodata.data[0].order_is_finished == 10041002) {
          this.auditFlag = false;
          this.inFlag = false;
          this.saveFlag = false;
          this.addFlag = false;
        } else if (infodata.data[0].order_is_finished == 10041001) {
          this.addFlag = false;
          this.auditFlag = true;
          this.inFlag = false;
          this.saveFlag = true;
          // 审核完，没入账可以作废
          if (infodata.data[0].order_is_finished != 10041001) {
            this.quitFlag = false;
          }
        }
        console.log('明细', infodata);
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '单据查询失败!' });
      }
    },
    async inStock() {
      if (this.selectRows.length > 0) {
        let str = '';
        for (const item of this.selectRows) {
          // if (item.IS_AUDIT == 10041002) {
          //   return this.$notify.error({ title: '提示信息', message: '单据审核未通过!' });
          // } else
          if (item.IS_FINISHED == 10041001) {
            return this.$notify.error({ title: '提示信息', message: '存在已出库数据!' });
          } else if (!item.ITEM_ID) {
            return this.$notify.error({ title: '提示信息', message: '存在未保存数据!' });
          } else {
            str += item.ITEM_ID + ',';
          }
        }
        str = str.slice(0, -1);
        let receiptNo = this.topFilterList.find(x => x.fieldName == 'receiptNo').initialValue;
        let res = await stockIn(receiptNo, str);
        if (res.resultCode == 200) {
          this.tableData = [];
          this.deleteRows = '';
          this.editRow = {};

          this.$notify.success({ title: '提示信息', message: '出库成功!' });
          await this.showOrderItemDetail(this.innerID);
          this.topFilterList[1].disabled = true;
          this.topFilterList[4].disabled = true;
          this.isFinished = true;
          this.createFlag = true;
          this.inFlag = false;
          this.printFlag = false;
          this.addFlag = false;
          this.returnFlag = false;
          this.quitFlag = true;
          this.cancelFlag = false;
          this.quitFlag = true;
          // 自动打印
          // let autoPrint = this.topFilterList.find(x => x.fieldName === 'needPrint').initialValue;
          // console.log(, '自动打印');

          // if (autoPrint == 'true') {
          //   this.print();
          // }
        }
      } else {
        this.$notify.error({ title: '提示信息', message: '请选择至少一条表格数据!' });
      }
      /* console.log(this.inTableListData.IS_AUDIT);
      if (this.inTableListData[0].IS_AUDIT == 10041002) {
        this.$notify.error({ title: '提示信息', message: '单据审核未通过!' });
        this.inFlag = true;
      } else {
        let info1 = await queryPartIfBelowZero({ dms_table: this.inTableListData });
        if (info1.resultCode != 200) {
          return;
        }
        let info2 = await stockIn(this.topFilterList[0].initialValue);
        if (info2.resultCode != 200) {
          return;
        }
        this.tableData = [];
        this.deleteRows = '';
        this.editRow = {};

        this.$notify.success({ title: '提示信息', message: '出库成功!' });
        await this.showOrderItemDetail(this.innerID);
        this.topFilterList[1].disabled = true;
        this.topFilterList[4].disabled = true;
        this.isFinished = true;
        this.createFlag = true;
        this.inFlag = true;
        this.printFlag = false;
        this.addFlag = true;
        this.returnFlag = false;
        this.quitFlag = true;
        this.cancelFlag = false;
        // this.quitFlag = true;
      } */
    },
    async cancel() {
      // let lossNo = this.topFilterList[0].initialValue;
      // let inventoryNo = this.topFilterList[1].initialValue;
      // if (lossNo || inventoryNo) {
      //   let res = await cancel({ lossNo: lossNo, inventoryNo: inventoryNo });
      // }
      this.createFlag = false;
      this.addFlag = true;
      this.returnFlag = true;
      this.saveFlag = true;
      this.cancelFlag = true;
      this.auditFlag = true;
      this.inFlag = true;
      this.topFilterList[0].disabled = false;
      this.topFilterList[1].disabled = true;
      this.topFilterList[2].disabled = true;
      this.topFilterList.forEach(element => {
        switch (element.fieldName) {
          case 'remark':
            element.disabled = true;
            break;

          default:
            break;
        }
      });
      // this.topFilterList[0].initialValue = '';
      // this.topFilterList[1].initialValue = undefined;
      // this.topFilterList[2].initialValue = '';
      // this.topFilterList[3].initialValue = '';
      // this.topFilterList[4].initialValue = '';
      this.$refs.topFilterFormPanel.RESET_FORM();
      this.tableData = [];
      this.deleteRows = '';
      this.quitFlag = true;
      this.isFinished = false;
      this.editRow = {};
    },
    // 获取所有人的信息
    async getDealerUser() {
      const res = await getDealerUser();
      this.cunUserList = res.data;
    },
    async quit() {
      let info = await deleteOrder(this.innerID);
      if (info.resultCode != 200) {
        return;
      }
      this.$notify.success({ title: '提示信息', message: '单据作废成功!' });
      this.cancel();
    },
    confirmTl(backRow) {
      const num = backRow['OUT_QUANTITY'];
      console.log('退料确定', num);
      const part_no = this.partInfo['PART_NO'];
      // 计算可退料数量
      const partArr = this.tableData.filter(item => {
        // 是否入账
        const isStorage = item.STORAGE_CODE == backRow.STORAGE_CODE;
        const isPart = item.PART_NO == backRow.PART_NO;
        // const isFinished = item['IS_FINISHED'] == '10041001';
        const isAvailable = isStorage && isPart;
        return isAvailable || (item['TL_FROM'] && isPart);
      });
      console.log('统计的', partArr);
      // 判断退料数量是否合法
      let numAvailable = 0;
      partArr.forEach(item => {
        numAvailable += Number(item['OUT_QUANTITY']);
      });
      numAvailable = Number(numAvailable.toFixed(2));
      console.log('计算可退料数量', partArr, { num, numAvailable });
      if (num > numAvailable) {
        // 退料数量大于可退数
        this.$notify({
          title: '警告',
          message: '退料数量不能大于出库数量',
          type: 'warning'
        });
        return;
      }
      // 退料合法 继续走下面
      const row = Object.assign({}, this.partInfo);
      row._uid = null;
      // 数量 金额 不含税金额 成本金额
      row.ITEM_ID = null;
      row['OUT_QUANTITY'] = -num;
      row['OUT_AMOUNT'] = -num * Number(row['OUT_PRICE'] || 0);
      row['COST_AMOUNT'] = -num * Number(row['COST_PRICE'] || 0);
      // row['PART_COST_AMOUNT'] = -num * Number(row['PART_COST_AMOUNT'] || 0);
      // row['ITEM_UPDATE_STATUS'] = 'A';
      row['IS_FINISHED'] = 10041002;
      console.log(`row['ITEM_UPDATE_STATUS']`, row['ITEM_UPDATE_STATUS']);
      row['TL_FROM'] = true;
      // this.tableData.push(row)
      this.innerTableData.EXECUTE_INSERT(row);
      // console.log(`tableData`,this.tableData[1]['ITEM_UPDATE_STATUS'])
      this.showReturn = false;
      console.log(this.tableData, 'this.tableData');
      return;
    },
    // 打印方法
    async print() {
      let params = {};
      if (this.selectRows && this.selectRows.length) {
        let temp = new Array();
        this.selectRows.forEach(e => {
          temp.push(e.ITEM_ID);
        });
        // console.log(1232, temp);
        params.ids = null;
        if (temp.length && temp.length > 1) {
          params.ids = temp.join("','");
        } else {
          params.ids = temp[0];
        }
        // console.log(params);
      }
      const res = await printData(this.cunId, params);
      let name = null;
      if (res.data.detailInfo.length > 0) {
        this.dy = true;
        this.SalesprintList = res.data;
        this.cunUserList.forEach(x => {
          if (this.SalesprintList.baseInfo.USER_ID == x.userId) {
            this.SalesprintList.baseInfo.USER_NAME = x.employeeName;
          }
          if (this.SalesprintList.baseInfo.RECEIPTOR == x.userId) {
            this.SalesprintList.baseInfo.RECEIPTOR_USER = x.employeeName;
          }
          if (this.SalesprintList.detailInfo[0].UPDATED_BY == x.userId) {
            name = x.employeeName;
          }
        });
        let orgDataList = this.topFilterList.find(item => item.fieldName === 'orgCode').itemList || [];
        let orgDataItem = this.topFilterList.find(item => item.fieldName === 'orgCode').initialValue;
        this.SalesprintList.baseInfo.RECEIPTOR_NAME = orgDataList.find(item => item.value == orgDataItem).text;
        this.SalesprintList.detailInfo[0].UPDATED_BY_USER = name;
        // console.log(this.SalesprintList.baseInfo.RECEIPTOR_NAME, 'sss');
        // 打印
        this.$nextTick(() => {
          this.$refs.print.EXCUTE_PRINT();
        });
      } else {
        this.$notify.error({ title: '提示', message: '没有可打印数据！' });
      }
    },
    edit(row) {
      this.formData = row;
      this.editShowFlag = true;
      this.saveFlag = false;
      this.cancelFlag = false;
    },
    setNewPartData(val) {
      for (let i = 0; i < this.inTableListData.length; i++) {
        if (this.inTableListData[i].PART_NO == val.PART_NO && this.inTableListData[i].STORAGE_CODE == val.STORAGE_CODE) {
          this.$notify({ title: '警告信息', message: '相同配件不可以重复添加！', type: 'warning' });
          return;
        }
      }
      val.IS_FINISHED = 10041002;
      this.innerTableData.EXECUTE_INSERT(val);
      this.$notify({ title: '提示', message: '添加成功！', type: 'success' });
      this.innerTableData.EXECUTE_RESET_HEIGHT();
      // 添加回显
    },
    editPartData(editVal) {
      this.showEditPart = false;
      for (var i = 0; i < this.inTableListData.length; i++) {
        if (this.inTableListData[i].index == editVal.editIndex) {
          this.inTableListData[i].OUT_QUANTITY = editVal.OUT_QUANTITY;
          this.inTableListData[i].OUT_PRICE = editVal.OUT_PRICE;
          this.inTableListData[i].OUT_AMOUNT = editVal.OUT_AMOUNT;
          this.inTableListData[i].COST_AMOUNT = editVal.COST_AMOUNT;
          this.inTableListData[i].FLAG = editVal.FLAG;
          this.inFlag = true;
          this.quitFlag = true;
          this.saveFlag = false;
          return;
        }
      }
    },
    setReceiptor(val) {
      this.topFilterList[1].initialValue = val[0].CUSTOMER_CODE;
      this.topFilterList[3].initialValue = val[0].CUSTOMER_NAME;
    },
    editHandle(row) {
      if (row.IS_FINISHED == '10041001') {
        this.$notify({ title: '提示信息', message: '该领用单已出库，不允许编辑', type: 'warning' });
      } else {
        if (row.OUT_QUANTITY > 0) {
          this.isReturn = false;
        } else {
          this.isReturn = true;
        }
        this.editRow = row;
        this.showEditPart = true;
      }
    },
    changeHandle(val) {
      this.saveData = val;
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.showAddNewPart = val;
      this.showSearchReceiptor = val;
      this.showSearchInternalReceive = val;
      this.showEditPart = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    addNewPartFun() {
      this.isReturn = false;
      this.inFlag = true;
      this.quitFlag = true;
      this.saveFlag = false;
      this.createFlag = true;
      this.showAddNewPart = true;
    },
    returnPartFun(val) {
      this.partInfo = val;
      // this.isReturn = true;
      this.inFlag = true;
      this.quitFlag = true;
      this.saveFlag = false;
      this.createFlag = true;
      this.showReturn = true;
    },
    searchInternalReceiveFun() {
      this.showSearchInternalReceive = true;
    },
    searchReceiptorFun() {
      this.showSearchReceiptor = true;
    },
    // 字符串的下划线格式转驼峰格式，eg：hello_world => helloWorld
    underline2Hump(str) {
      var str1 = str.toLowerCase();
      while (str1.indexOf('_') != -1) {
        str1 = str1.replace(/_\w/, str1.substr(str1.indexOf('_') + 1, 1).toUpperCase());
      }
      return str1;
    },
    // JSON对象的key值转换为驼峰式
    jsonToHump(obj) {
      if (obj instanceof Array) {
        obj.forEach((v, i) => {
          this.jsonToHump(v);
        });
      } else if (obj instanceof Object) {
        Object.keys(obj).forEach(key => {
          var newKey = this.underline2Hump(key);
          if (newKey !== key) {
            obj[newKey] = obj[key];
            delete obj[key];
          }
          this.jsonToHump(obj[newKey]);
        });
      }
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJNL'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
        this.printParams.vDirectPrint = this.printParams.vDirectPrint === 0 ? '0' : this.printParams.vDirectPrin;
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style lang="less" scoped></style>
